/*
 * SPDX-FileCopyrightText: 2019-2021 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include "esp_eth_phy_ch182.h"
#include "tcp_log.h"
#define TAG "ch182"

void print_phy(char* PHY_name, uint32_t PHY_val)
{
    ESP_LOGW(PHY_name, "origin val = 0x%x, bit val: %d%d%d%d  %d%d%d%d  %d%d%d%d  %d%d%d%d",
        PHY_val,
        (PHY_val >> 15) & 0x01,
        (PHY_val >> 14) & 0x01,
        (PHY_val >> 13) & 0x01,
        (PHY_val >> 12) & 0x01,
        (PHY_val >> 11) & 0x01,
        (PHY_val >> 10) & 0x01,
        (PHY_val >> 9) & 0x01,
        (PHY_val >> 8) & 0x01,
        (PHY_val >> 7) & 0x01,
        (PHY_val >> 6) & 0x01,
        (PHY_val >> 5) & 0x01,
        (PHY_val >> 4) & 0x01,
        (PHY_val >> 3) & 0x01,
        (PHY_val >> 2) & 0x01,
        (PHY_val >> 1) & 0x01,
        (PHY_val >> 0) & 0x01);
}
/***************List of Supported Models***************/

/***************Vendor Specific Register***************/

static esp_err_t ch182_update_link_duplex_speed(phy_ch182_t* ch182)
{
    esp_err_t ret = ESP_OK;
    esp_eth_mediator_t* eth = ch182->eth;
    eth_speed_t speed = ETH_SPEED_10M;
    eth_duplex_t duplex = ETH_DUPLEX_HALF;
    bmsr_reg_t bmsr;
    pscsr_reg_t pscsr;
    uint32_t peer_pause_ability = false;
    anlpar_reg_t anlpar;
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_ANLPAR_REG_ADDR, &(anlpar.val)), err, TAG, "read ANLPAR failed");
    // printf("\nanlpar.val %08x \n", anlpar.val);
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_BMSR_REG_ADDR, &(bmsr.val)), err, TAG, "read BMSR failed");
    // printf("\nbmsr.val %08x \n", bmsr.val);
    eth_link_t link = bmsr.link_status ? ETH_LINK_UP : ETH_LINK_DOWN;
    if (PHY_LOG) {
        ESP_LOGI(TAG, "ch182_update_link_duplex_speed");
        print_phy("PHY_REG_5", anlpar.val);
        print_phy("PHY_REG_1", bmsr.val);
        ESP_LOGI("PHY", "Link status = %d", bmsr.link_status);
    }
    // printf("\nbmsr.link_status %08x \n", bmsr.link_status);
    /* check if link status changed */
    if (ch182->link_status != link) {
        /* when link up, read negotiation result */
        // printf("\nlink %08x \n", link);
        if (link == ETH_LINK_UP) {
            ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_CH182_PHY_STATUS_REG_ADDR, &(pscsr.val)), err, TAG, "read PSCSR failed");
            // printf("\npscsr.val %08x \n", pscsr.val);
            if (PHY_LOG) {
                ESP_LOGW("PHY", "Link up");
                print_phy("PHY_REG_0", pscsr.val);
            }
            if (pscsr.val & (1 << 13)) {
                speed = ETH_SPEED_100M;
            } else {
                speed = ETH_SPEED_10M;
            }
            if (pscsr.val & (1 << 8)) {
                duplex = ETH_DUPLEX_FULL;
            } else {
                duplex = ETH_DUPLEX_HALF;
            }
            ESP_GOTO_ON_ERROR(eth->on_state_changed(eth, ETH_STATE_SPEED, (void*)speed), err, TAG, "change speed failed");
            ESP_GOTO_ON_ERROR(eth->on_state_changed(eth, ETH_STATE_DUPLEX, (void*)duplex), err, TAG, "change duplex failed");
            /* if we're in duplex mode, and peer has the flow control ability */
            if (duplex == ETH_DUPLEX_FULL && anlpar.symmetric_pause) {
                peer_pause_ability = 1;
            } else {
                peer_pause_ability = 0;
            }
            ESP_GOTO_ON_ERROR(eth->on_state_changed(eth, ETH_STATE_PAUSE, (void*)peer_pause_ability), err, TAG, "change pause ability failed");
        }
        ESP_GOTO_ON_ERROR(eth->on_state_changed(eth, ETH_STATE_LINK, (void*)link), err, TAG, "change link failed");
        ch182->link_status = link;
    }
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_set_mediator(esp_eth_phy_t* phy, esp_eth_mediator_t* eth)
{
    esp_err_t ret = ESP_OK;
    ESP_GOTO_ON_FALSE(eth, ESP_ERR_INVALID_ARG, err, TAG, "can't set mediator to null");
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    ch182->eth = eth;
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_get_link(esp_eth_phy_t* phy)
{
    esp_err_t ret = ESP_OK;
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    if (PHY_LOG) {
        ESP_LOGI(TAG, "ch182_get_link");
    }
    /* Updata information about link, speed, duplex */
    ESP_GOTO_ON_ERROR(ch182_update_link_duplex_speed(ch182), err, TAG, "update link duplex speed failed");
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_reset(esp_eth_phy_t* phy)
{
    if (PHY_LOG) {
        ESP_LOGI(TAG, "ch182_reset");
    }
    esp_err_t ret = ESP_OK;
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    ch182->link_status = ETH_LINK_DOWN;
    esp_eth_mediator_t* eth = ch182->eth;
    bmcr_reg_t bmcr = { .reset = 1 };
    ESP_GOTO_ON_ERROR(eth->phy_reg_write(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, bmcr.val), err, TAG, "write BMCR failed");
    /* wait for reset complete */
    uint32_t to = 0;
    for (to = 0; to < ch182->reset_timeout_ms / 10; to++) {
        vTaskDelay(pdMS_TO_TICKS(10));
        ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)), err, TAG, "read BMCR failed");
        if (!bmcr.reset) {
            break;
        }
    }
    ESP_GOTO_ON_FALSE(to < ch182->reset_timeout_ms / 10, ESP_FAIL, err, TAG, "reset timeout");
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_reset_hw(esp_eth_phy_t* phy)
{
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    ESP_LOGI(TAG, "ch182 reset hardware!");
    if (ch182->reset_gpio_num >= 0) {
        esp_rom_gpio_pad_select_gpio(ch182->reset_gpio_num);
        gpio_set_direction(ch182->reset_gpio_num, GPIO_MODE_OUTPUT);
        gpio_set_level(ch182->reset_gpio_num, 0);
        /* assert nRST signal on ch182 a little longer than the minimum specified in datasheet */
        esp_rom_delay_us(150);
        gpio_set_level(ch182->reset_gpio_num, 1);
    }
    return ESP_OK;
}

/**
 * @note This function is responsible for restarting a new auto-negotiation,
 *       the result of negotiation won't be relected to uppler layers.
 *       Instead, the negotiation result is fetched by linker timer, see `ch182_get_link()`
 */
static esp_err_t ch182_negotiate(esp_eth_phy_t* phy)
{
    esp_err_t ret = ESP_OK;
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    esp_eth_mediator_t* eth = ch182->eth;
    /* in case any link status has changed, let's assume we're in link down status */
    ch182->link_status = ETH_LINK_DOWN;
    /* Restart auto negotiation */
    bmcr_reg_t bmcr = {
        .speed_select = 1, /* 100Mbps */
        .duplex_mode = 1, /* Full Duplex */
        .en_auto_nego = 1, /* Auto Negotiation */
        .restart_auto_nego = 1 /* Restart Auto Negotiation */
    };
    ESP_GOTO_ON_ERROR(eth->phy_reg_write(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, bmcr.val), err, TAG, "write BMCR failed");
    /* Wait for auto negotiation complete */
    bmsr_reg_t bmsr;
    pscsr_reg_t pscsr;
    uint32_t to = 0;
    for (to = 0; to < ch182->autonego_timeout_ms / 100; to++) {
        vTaskDelay(pdMS_TO_TICKS(100));
        ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_BMSR_REG_ADDR, &(bmsr.val)), err, TAG, "read BMSR failed");
        ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_CH182_PHY_STATUS_REG_ADDR, &(pscsr.val)), err, TAG, "read PSCSR failed");
        if (bmsr.auto_nego_complete && pscsr.auto_nego_done) {
            break;
        }
    }
    /* Auto negotiation failed, maybe no network cable plugged in, so output a warning */
    if (to >= ch182->autonego_timeout_ms / 100 && (ch182->link_status == ETH_LINK_UP)) {
        ESP_LOGW(TAG, "auto negotiation timeout");
    }
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_pwrctl(esp_eth_phy_t* phy, bool enable)
{
    esp_err_t ret = ESP_OK;
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    esp_eth_mediator_t* eth = ch182->eth;
    bmcr_reg_t bmcr;
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)), err, TAG, "read BMCR failed");
    if (!enable) {
        /* General Power Down Mode */
        bmcr.power_down = 1;
    } else {
        /* Normal operation Mode */
        bmcr.power_down = 0;
    }
    ESP_GOTO_ON_ERROR(eth->phy_reg_write(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, bmcr.val), err, TAG, "write BMCR failed");
    if (!enable) {
        ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)), err, TAG, "read BMCR failed");
        ESP_GOTO_ON_FALSE(bmcr.power_down == 1, ESP_FAIL, err, TAG, "power down failed");
    } else {
        /* wait for power up complete */
        uint32_t to = 0;
        for (to = 0; to < ch182->reset_timeout_ms / 10; to++) {
            vTaskDelay(pdMS_TO_TICKS(10));
            ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)), err, TAG, "read BMCR failed");
            if (bmcr.power_down == 0) {
                break;
            }
        }
        ESP_GOTO_ON_FALSE(to < ch182->reset_timeout_ms / 10, ESP_FAIL, err, TAG, "power up timeout");
    }
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_set_addr(esp_eth_phy_t* phy, uint32_t addr)
{
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    ch182->addr = addr;
    return ESP_OK;
}

static esp_err_t ch182_get_addr(esp_eth_phy_t* phy, uint32_t* addr)
{
    esp_err_t ret = ESP_OK;
    ESP_GOTO_ON_FALSE(addr, ESP_ERR_INVALID_ARG, err, TAG, "addr can't be null");
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    *addr = ch182->addr;
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_del(esp_eth_phy_t* phy)
{
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    free(ch182);
    return ESP_OK;
}

static esp_err_t ch182_advertise_pause_ability(esp_eth_phy_t* phy, uint32_t ability)
{
    esp_err_t ret = ESP_OK;
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    esp_eth_mediator_t* eth = ch182->eth;
    /* Set PAUSE function ability */
    anar_reg_t anar;
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_ANAR_REG_ADDR, &(anar.val)), err, TAG, "read ANAR failed");
    if (ability) {
        anar.asymmetric_pause = 1;
        anar.symmetric_pause = 1;
    } else {
        anar.asymmetric_pause = 0;
        anar.symmetric_pause = 0;
    }
    ESP_GOTO_ON_ERROR(eth->phy_reg_write(eth, ch182->addr, ETH_PHY_ANAR_REG_ADDR, anar.val), err, TAG, "write ANAR failed");
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_loopback(esp_eth_phy_t* phy, bool enable)
{
    esp_err_t ret = ESP_OK;
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    esp_eth_mediator_t* eth = ch182->eth;
    /* Set Loopback function */
    bmcr_reg_t bmcr;
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)), err, TAG, "read BMCR failed");
    if (PHY_LOG) {
        ESP_LOGI(TAG, "ch182_loopback");
        print_phy("PHY_REG_0", bmcr.val);
    }
    if (enable) {
        bmcr.en_loopback = 1;
    } else {
        bmcr.en_loopback = 0;
    }
    ESP_GOTO_ON_ERROR(eth->phy_reg_write(eth, ch182->addr, ETH_PHY_BMCR_REG_ADDR, bmcr.val), err, TAG, "write BMCR failed");
    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_init(esp_eth_phy_t* phy)
{
    esp_err_t ret = ESP_OK;
    uint32_t x;
    phy_ch182_t* ch182 = __containerof(phy, phy_ch182_t, parent);
    esp_eth_mediator_t* eth = ch182->eth;
    // Detect PHY address
    if (ch182->addr == ESP_ETH_PHY_ADDR_AUTO) {
        ESP_GOTO_ON_ERROR(esp_eth_detect_phy_addr(eth, &ch182->addr), err, TAG, "Detect PHY address failed");
    }
    /* Power on Ethernet PHY */
    ESP_GOTO_ON_ERROR(ch182_pwrctl(phy, true), err, TAG, "power control failed");
    /* Reset Ethernet PHY */
    ESP_GOTO_ON_ERROR(ch182_reset(phy), err, TAG, "reset failed");
    /* Check PHY ID */
    phyidr1_reg_t id1;
    phyidr2_reg_t id2;
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_IDR1_REG_ADDR, &(id1.val)), err, TAG, "read ID1 failed");
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, ETH_PHY_IDR2_REG_ADDR, &(id2.val)), err, TAG, "read ID2 failed");
    // printf("\nid1:%x  id2:%x\n", id1.val, id2.val);
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, 0x00, &x), err, TAG, "read page reg failed");
    // printf("\nxxxxx:%x  id2:%x\n", x, x);
    ESP_GOTO_ON_ERROR(eth->phy_reg_write(eth, ch182->addr, 0x00, 0x200), err, TAG, "write page failed");
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, 0x17, &x), err, TAG, "read page reg failed");
    // printf("\nxxxx:%x  id2:%x\n", x, x);
    ESP_GOTO_ON_ERROR(eth->phy_reg_read(eth, ch182->addr, 0x10, &x), err, TAG, "read rmii failed");
    // printf("\nxxxx:%x  id2:%x\n", x, x);
    //  ESP_GOTO_ON_FALSE(id1.val == 0x7371 && id2.val == 0x9011, ESP_FAIL, err, TAG, "wrong chip ID");

    return ESP_OK;
err:
    return ret;
}

static esp_err_t ch182_deinit(esp_eth_phy_t* phy)
{
    esp_err_t ret = ESP_OK;
    /* Power off Ethernet PHY */
    ESP_GOTO_ON_ERROR(ch182_pwrctl(phy, false), err, TAG, "power control failed");
    return ESP_OK;
err:
    return ret;
}

esp_eth_phy_t* esp_eth_phy_new_ch182(const eth_phy_config_t* config)
{
    esp_eth_phy_t* ret = NULL;
    ESP_GOTO_ON_FALSE(config, NULL, err, TAG, "can't set phy config to null");
    phy_ch182_t* ch182 = calloc(1, sizeof(phy_ch182_t));
    ESP_GOTO_ON_FALSE(ch182, NULL, err, TAG, "calloc ch182 failed");
    ch182->addr = config->phy_addr;
    ch182->reset_gpio_num = config->reset_gpio_num;
    ch182->reset_timeout_ms = config->reset_timeout_ms;
    ch182->link_status = ETH_LINK_DOWN;
    ch182->autonego_timeout_ms = config->autonego_timeout_ms;
    ch182->parent.reset = ch182_reset;
    ch182->parent.reset_hw = ch182_reset_hw;
    ch182->parent.init = ch182_init;
    ch182->parent.deinit = ch182_deinit;
    ch182->parent.set_mediator = ch182_set_mediator;
    ch182->parent.negotiate = ch182_negotiate;
    ch182->parent.get_link = ch182_get_link;
    ch182->parent.pwrctl = ch182_pwrctl;
    ch182->parent.get_addr = ch182_get_addr;
    ch182->parent.set_addr = ch182_set_addr;
    ch182->parent.loopback = ch182_loopback;
    ch182->parent.advertise_pause_ability = ch182_advertise_pause_ability;
    ch182->parent.del = ch182_del;

    return &(ch182->parent);
err:
    return ret;
}
